<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Admin_AccessController extends Zend_Controller_Action
{

    private $_accessService;
    private $_memberService;
    private $_memberAccessService;

    public function init()
    {
        $this->_accessService = $this->_helper->getService('Core_Service_Access');
        $this->_memberService = $this->_helper->getService('Core_Service_Member');
        $this->_memberAccessService = $this->_helper->getService('Core_Service_MemberAccess');
    }

    public function indexAction()
    {
        $this->view->access = $this->_accessService->fetchAllAccess(false);
        //$this->view->member = $this->_memberService->fetchAll
    }

    public function createAction()
    {
        $this->_helper->acl()->isAllowed('service:access', 'create');
        $form = new Admin_Form_Access_AddArea();
        $request = $this->getRequest();

        if ($request->isPost() && $form->isValid($request->getPost()))
        {
            $result = $this->_accessService->create($form->getValues());
            if ($result) {
                $this->view->flashMessage()->addMessage('La til et nytt område', RedCross_View_Helper_FlashMessage::SUCCESS);
                return $this->_helper->redirector('index');
            } else {
                $this->view->unknownError = true;
            }
        }
        $this->view->form = $form;
    }

    public function editAction()
    {
        $this->_helper->acl()->isAllowed('service:access', 'edit');

        $access_id = $this->_getParam('id');

        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($access_id)) {
            throw new RedCross_Exception_ValidationFailed();
        }
        $access_id = (int)$access_id;

        $access = $this->_accessService->fetch($access_id);
        $editForm = new Admin_Form_Access_Edit();
        $editForm->fillForm($access);

        $request = $this->getRequest();
        if ($request->isPost())
        {
            $values = $request->getPost();

            // Editing course information
            if ($values['action'] === Admin_Form_Access_Edit::ACTION && $editForm->isValid($values))
            {
                $result = $this->_accessService->edit($access_id, $editForm->getValues());
                if ($result === true) {
                    $this->view->flashMessage()->addMessage('Område oppdatert', RedCross_View_Helper_FlashMessage::SUCCESS);
                    return $this->_helper->redirector('index');
                } else {
                    $this->view->unknownError = true;
                }
            }
        }

        $this->view->access = $access;
        $this->view->editForm = $editForm;

        // Populate list of members 
        $filterContent = array(
            'has_access' => 'Medlemmer som skal ha tilgang til området',
            'no_access'  => 'Medlemmer som ikke skal ha tilgang til området',
        );        
        $filterForm = $this->view->filterForm = $this->view->filterForm($filterContent);
        $filterForm->setAction($this->view->url(array('module' => 'admin', 'controller' => 'access', 'action' => 'edit'), null, false));

        if ($request->isGet() && $this->_getParam('filter', false) && $filterForm->isValid($request->getQuery())) {
            $value = $filterForm->getValue('filter');
            switch ($value) {
            case 'has_access':
                $this->view->members = $this->_accessService->fetchMembersWithAccess($access_id);
                break;
            case 'no_access':
                $this->view->members = $this->membersWithoutAccess($access_id);
                break;
            }
        }

        if (!isset($this->view->members)) {
            $this->view->members = $this->_accessService->fetchMembersWithAccess($access_id);
        }
    }

    private function membersWithoutAccess($access_id) {
        $withAccess = $this->_accessService->fetchMembersWithAccess($access_id)->getData();
        $allMembers = $this->_memberService->fetchAllActive()->getData();
        return array_diff($allMembers, $withAccess);
    }
    public function editmembersAction() {
        $this->_helper->acl()->isAllowed('service:member', 'editCourses');

        $access_id = $this->_getParam('id');
        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($access_id)) {
            throw new RedCross_Exception_ValidationFailed();
        }
        $access_id = (int)$access_id;
        $area = $this->_accessService->fetch($access_id);

        $request = $this->getRequest();
        if ($request->isPost())
        {
            $values = $request->getPost();

            // Adding members to access
            if ($values['submit'] === "Legg til valgte")
            {
                $members = array();
                foreach ($values['members'] as $memberId) {
                    if (!$validator->isValid($memberId)) {
                        throw new RedCross_Exception_ValidationFailed();
                    }
                    $memberId = (int)$memberId;
                    $member = $this->_memberService->fetchById($memberId);

                    $accessAdded = $this->_memberService->addAccess($memberId, array('access' => $access_id));

                    if (is_object($accessAdded)) {
                        $members[$memberId] = $member;
                        $this->view->flashMessage()->addMessage($member->first_name . ' ' . $member->last_name . ' ble tildelt adgang', RedCross_View_Helper_FlashMessage::SUCCESS);
                    } else {
                        $this->view->flashMessage()->addMessage($member->first_name . ' ' . $member->last_name . ' ble ikke tildelt adgang', RedCross_View_Helper_FlashMessage::ERROR);
                    }
                }
                $this->sendAccessMail($members, $area, "access-granted.phtml");
            }

            else if ($values['submit'] === "Fjern valgte")
            {
                $members = array();
                foreach ($values['members'] as $memberId) {
                    if (!$validator->isValid($memberId)) {
                        throw new RedCross_Exception_ValidationFailed();
                    }
                    $memberId = (int)$memberId;
                    $member = $this->_memberService->fetchById($memberId);
                    $accessRemoved = $this->_memberAccessService->removeAccess($memberId, $access_id);

                    if ($accessRemoved != null) {
                        $members[$memberId] = $member;
                        $this->view->flashMessage()->addMessage($member->first_name . ' ' . $member->last_name . ' ble fratatt adgang', RedCross_View_Helper_FlashMessage::SUCCESS);
                    } else {
                        $this->view->flashMessage()->addMessage($member->first_name . ' ' . $member->last_name . ' ble ikke fratatt adgang', RedCross_View_Helper_FlashMessage::ERROR);
                    }
                }
                $this->sendAccessMail($members, $area, "access-revoked.phtml");
            }
        }
        
        return $this->_helper->redirector('edit', null, null, array('id' => $access_id));
    }


    private function sendAccessMail($members, $area, $template) {
        $mail = new RedCross_Mail_Base();
        $mail->setSubject('Endre adgang på følgende medlemmer');

        $config = $config = Zend_Registry::get('config');
        $toName = $config['rk']['access']['recipient']['name'];
        $toAddr = $config['rk']['access']['recipient']['address'];

        $mail->addTo($toAddr, $toName);

        $content = new Zend_View();
        $content->setScriptPath(APPLICATION_PATH . '/layouts/main/emails/');
        $content->assign('members', $members);
        $content->assign('area', $area);

        $body = $content->render($template);
        try {
            $mail->setBodyText($body);
            $mail->send();
        } catch (Exception $e) {
            $this->view->flashMessage()->addMessage('Kunne ikke sende epost.', RedCross_View_Helper_FlashMessage::ERROR);
        }
    }
}
